import { createApp } from 'vue'
import { createPinia } from 'pinia'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import 'element-plus/theme-chalk/dark/css-vars.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import 'nprogress/nprogress.css'

import App from './App.vue'
import router from './router'
import { useUserStore } from '@/stores/user'
import '@/styles/index.scss'

// 创建应用实例
const app = createApp(App)

// 注册Element Plus图标
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component)
}

// 注册插件
app.use(createPinia())
app.use(router)
app.use(ElementPlus, {
  locale: zhCn,
  size: 'default'
})

// 初始化用户信息
const initApp = async () => {
  const userStore = useUserStore()

  // 如果有token，尝试初始化用户信息
  if (userStore.token) {
    try {
      await userStore.initUserInfo()
    } catch (error) {
      console.warn('初始化用户信息失败:', error)
      // 不要在这里清除token，让路由守卫处理
    }
  }

  // 挂载应用
  app.mount('#app')
}

// 启动应用
initApp().catch(console.error)
